using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Log;
using GrapeCity.Forguncy.Plugin;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;

namespace TaskSyncOperation
{
    [Icon("pack://application:,,,/TaskSyncOperation;component/Resources/Icon_Info.png")]
    [Designer("TaskSyncOperation.Designer.TaskSyncOperationServerCommandDesigner, TaskSyncOperation")]
    [Category("异步调用")]
    public class RegistryTask : Command, ICommandExecutableInServerSideAsync, ISubListCommand, IContainSubCommands
    {
        [Browsable(false)]
        public List<Command> CommandList { get; set; } = new List<Command>();

        public IEnumerable<List<Command>> EnumSubCommands()
        {
            yield return CommandList;
        }

        [ResultToProperty]
        [DisplayName("将任务标识保存到：")]
        public string ResultTo { get; set; } = "任务标识";

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            string taskId = Guid.NewGuid().ToString();

            // 注册任务，不立即执行
            TaskRunner.Instance.AddTask(taskId, () => dataContext.ExecuteCommandsAsync(this.CommandList));

            dataContext.Parameters[ResultTo] = taskId;

            return new ExecuteResult();

        }

        public override string ToString()
        {
            return "注册异步任务";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
}
